package com.example.consumer;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.time.Duration;
import java.util.ArrayList;
import java.util.Properties;

/**
 * Created with IntelliJ IDEA.
 * ClassName: CustomConsumer
 * Package: com.example.consumer
 * Description:
 * User: fzykd
 *
 * @Author: LQH
 * Date: 2023-08-02
 * Time: 18:34
 */

//自定义消费者
public class CustomConsumer1 {
    public static void main(String[] args) {

        //0.配置
        Properties properties = new Properties();

        //必须配置的参数
        //连接
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"hadoop102:9092");
        //反序列化
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,StringDeserializer.class.getName());

        //一个消费者 也要配置消费者组ID 名字随便起 但是必须要有
        properties.put(ConsumerConfig.GROUP_ID_CONFIG,"test");

        // 修改分区分配策略
        properties.put(ConsumerConfig.PARTITION_ASSIGNMENT_STRATEGY_CONFIG, "org.apache.kafka.clients.consumer.RoundRobinAssignor");


        //1.创建一个消费者 "","hello"
        KafkaConsumer<String, String> consumer = new KafkaConsumer<>(properties);

        //2.订阅主题 first
        ArrayList<String> topics = new ArrayList<>();
        topics.add("first");
        consumer.subscribe(topics); //参数是一个集合 可以消费多个主题

        //3.消费数据
        while (true){
            //拉取数据 1秒拉取一次
            ConsumerRecords<String, String> poll = consumer.poll(Duration.ofSeconds(1));
            for (ConsumerRecord<String, String> consumerRecord : poll) {
                System.out.println(consumerRecord);
            }
        }
    }
}
